import React from 'react'
import { FC, useState, useEffect } from 'react'
import { Menu } from 'antd'
import axios from 'axios'
// store
import { appShallowEqual, useAppSelector, useAppDispatch } from '@/stores'
import { changeSelectedKey, setMusicGroup } from '@/stores/modules/music'
// type
import type { MenuProps } from 'antd'
type MenuItem = Required<MenuProps>['items'][number]
interface ItemType {
  name: string
  id: string
  image: string
  time: string
}
interface ItemParentType extends ItemType {
  children?: ItemType[]
}

const MusicListSide: FC = () => {
  const [musicGroups, setMusicGroups] = useState<ItemType[]>([])
  const [items, setItems] = useState<MenuProps['items']>([])
  const [openKeys, setOpenKeys] = useState([''])
  const { selectedKey } = useAppSelector((state) => ({ selectedKey: state.musicReducer.selectedKey }), appShallowEqual)
  const dispatch = useAppDispatch()
  const getItem = (
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
    type?: 'group'
  ): MenuItem => {
    return {
      key,
      icon,
      children,
      label,
      type
    } as MenuItem
  }
  useEffect(() => {
    axios.get('http://localhost:4000/musicGroup').then((res) => {
      const group: ItemType[] = []
      const { data } = res
      const items = data.map((item: ItemParentType) => {
        const { name, id, children } = item
        if (!children) group.push(item)
        const childArr = children?.map((child: ItemType) => {
          group.push(child)
          const { name, id } = child
          return getItem(name, id)
        })
        return getItem(name, id, null, childArr)
      })
      setMusicGroups(group)
      dispatch(setMusicGroup(data[0]))
      dispatch(changeSelectedKey(data[0]?.id))
      setItems(items)
    })
  }, [])
  const onOpenChange: MenuProps['onOpenChange'] = (keys) => {
    setOpenKeys(keys)
  }
  const onSelect: MenuProps['onSelect'] = ({ key }) => {
    const group = musicGroups.find((item) => item.id === key)
    dispatch(changeSelectedKey(key))
    dispatch(setMusicGroup(group))
  }
  return (
    <Menu
      mode="inline"
      onSelect={onSelect}
      selectedKeys={[selectedKey]}
      openKeys={openKeys}
      onOpenChange={onOpenChange}
      items={items}
    />
  )
}
export default MusicListSide
